<script setup>
import instance from "../instance";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {dayjs, ElMessage} from "element-plus";

//页面和容量
const page = ref(1)
const pageSize = ref(10)
const total = ref(0);
const tableData = ref([])
const tableDataEmp = ref([])
const emps = ref([])

const handleSizeChange = (val) => {
  pageSize.value = val
  findClasses()
}
const handleCurrentChange = (val) => {
  page.value = val
  findClasses()
}


onMounted(() => {
  findClasses()
  findEmp()
})


const findEmp = () => {
  instance.get('/emps?page=1&pageSize=100').then(res => {
    tableDataEmp.value = res.data.data.rows
    updataEmp()
  })
}
const updataEmp = () => {
  for (let i = 0; i < tableDataEmp.value.length; i++) {
    const data = {
      value: tableDataEmp.value[i].id,
      label: tableDataEmp.value[i].name
    }
    emps.value.push(data)
  }
}


const findClasses = () => {
  let url = '/classes?page=' + page.value + '&pageSize=' + pageSize.value
  if (formInline.name !== '') {
    url = url + "&name=" + formInline.name
  }
  if (formInline.begin !== '') {
    url = url + "&begin=" + formInline.begin
  }
  if (formInline.end !== '') {
    url = url + "&end=" + formInline.end
  }
  instance.get(url)
      .then(function (res) {
        // 处理成功情况
        tableData.value = res.data.data.rows;
        total.value = res.data.data.total
      })
      .catch(function (error) {
        // 处理错误情况
        console.log(error);
      })
}

const formInline = reactive({
  name: '',
  begin: '',
  end: '',
})


const value1 = ref('')
//格式化时间
watch(value1, (newVal) => {
  if (newVal && newVal.length === 2) {
    formInline.begin = dayjs(newVal[0]).format('YYYY-MM-DD');
    formInline.end = dayjs(newVal[1]).format('YYYY-MM-DD');
  } else {
    formInline.begin = '';
    formInline.end = '';
  }
});

const onSubmit = () => {
  findClasses()
}
const onClean = () => {
  window.location.reload();
}
//增加教室信息
const dialogFormAdd = ref(false)
const addForm = ref({
  name: '',
  classesNumber: '',
  startTime: '',
  finishTime: '',
  empId: '',
})
const addClasses = () => {
  addForm.value = {
    name: '',
    classesNumber: '',
    startTime: '',
    finishTime: '',
    empId: '',
  }
  dialogFormAdd.value = true
}

const formattedBegin = ref('')
watch(formattedBegin, (newVal) => {
  if (newVal) {
    addForm.value.startTime = dayjs(newVal).format('YYYY-MM-DD');
  } else {
    addForm.value.startTime = '';
  }
});

const formattedEnd = ref('');
watch(formattedEnd, (newVal) => {
  if (newVal) {
    addForm.value.finishTime = dayjs(newVal).format('YYYY-MM-DD');
  } else {
    addForm.value.finishTime = '';
  }
});

const addClassesOk = () => {
  const classes = addForm.value
  if (classes.name === '' || classes.classesNumber === '' || classes.startTime === '' || classes.finishTime === '', classes.empId === '') {
    ElMessage({
      message: '还有信息没填',
      type: 'warning',
    })
  } else {
    instance.post('/classes', classes)
        .then(res => {
          if (res.data.code === 0) {
            ElMessage.error(res.data.msg)
          } else {
            ElMessage({
              message: '添加成功',
              type: 'success',
            })
            findClasses()
            dialogFormAdd.value = false
          }
        }).catch(error => {
      console.error('添加失败：', error);
    });
  }
}

//删除教室
const dialogVisibleClass = ref(false)
const classesById = ref('')
const removeclassById = (id) => {
  classesById.value = ''
  dialogVisibleClass.value = true
  classesById.value = id
}
const removeclassByIdOk = () => {
  instance.delete('/classes/' + classesById.value)
      .then(res => {
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
        } else {
          ElMessage({
            message: '删除成功',
            type: 'success',
          })
          findClasses() //删除成功后重新查询
        }

      })
      .catch(error => {
        console.error('删除失败：', error);
      });
  dialogVisibleClass.value = false
}

//修改
const dialogFormUpdata = ref(false)
const updataForm = ref({
  id: '',
  name: '',
  classesNumber: '',
  startTime: '',
  finishTime: '',
  empId: '',
})
const updataClasses = (id) => {
  instance.get('/classes/' + id)
      .then(res => {
        updataForm.value = {
          id: res.data.data.id,
          name: res.data.data.name,
          classesNumber: res.data.data.classesNumber,
          startTime: res.data.data.startTime,
          finishTime: res.data.data.finishTime,
          empId: res.data.data.empId,
        }
      })
  dialogFormUpdata.value=true
}
const updataClassesOk =()=>{
  instance.put('/classes',updataForm.value)
      .then(res => {
        if (res.data.code === 0) {
          ElMessage.error(res.data.msg)
        } else {
          findClasses()
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dialogFormUpdata.value=false
        }
      })
      .catch(error => {
        console.error('修改失败：', error);
      });
}

</script>


<template>

  <!--  查询表单  -->
  <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="教室名称">
      <el-input v-model="formInline.name" placeholder="请输入教室名称" clearable/>
    </el-form-item>
    <el-form-item label="结束时间">
      <el-date-picker
          v-model="value1"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :size="size"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onClean">清除</el-button>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
      <el-button type="primary" @click="addClasses">新增班级</el-button>
    </el-form-item>
  </el-form>


  <br>


  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column prop="name" label="班级名称" width="220"/>
    <el-table-column prop="classesNumber" label="班级教室" width="180"/>
    <el-table-column prop="startTime" label="开课时间" width="200"/>
    <el-table-column prop="finishTime" label="结束时间" width="200"/>
    <el-table-column prop="empName" label="班主任" width="180"/>
    <el-table-column fixed="right" label="操作" width="200">
      <template #default="scope">
        <el-button :plain="true" type="primary" plain @click="updataClasses(scope.row.id)">修改</el-button>
        <el-button type="danger" plain @click="removeclassById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <hr>
  <!--    分页   -->
  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 删除提示对话框  -->
  <el-dialog
      v-model="dialogVisibleClass"
      title="删除教室"
      width="30%"
  >
    <span>是否要删除此教室</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisibleClass = false">取消删除</el-button>
        <el-button :plain="true" type="primary" @click="removeclassByIdOk()">
          确认删除
        </el-button>
      </span>
    </template>
  </el-dialog>


  <!--添加教室表单-->
  <el-dialog v-model="dialogFormAdd" title="新增班级">
    <el-form :model="addForm">
      <el-form-item label="班级名称">
        <el-input v-model="addForm.name" placeholder="请输入班级名称"/>
      </el-form-item>
      <el-form-item label="班级教室">
        <el-input v-model="addForm.classesNumber" placeholder="请输入班级教室"/>
      </el-form-item>
      <el-form-item label="开课时间">
        <el-date-picker
            v-model="formattedBegin"
            type="date"
            placeholder="请选择开课时间"
            :size="size"
        />
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker
            v-model="formattedEnd"
            type="date"
            placeholder="请选择结课时间"
            :size="size"
        />
      </el-form-item>
      <el-form-item label="班主任">
        <el-select
            style="width: 200px"
            v-model="addForm.empId"
            placeholder="请选择班主任"
            clearable
        >
          <el-option
              v-for="(item, index) in emps"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormAdd = false">取消</el-button>
        <el-button :plain="true" type="primary" @click="addClassesOk">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>


  <!--修改教室表单-->
  <el-dialog v-model="dialogFormUpdata" title="修改班级">
    <el-form :model="updataForm">
      <el-form-item label="班级名称">
        <el-input v-model="updataForm.name" placeholder="请输入班级名称"/>
      </el-form-item>
      <el-form-item label="班级教室">
        <el-input v-model="updataForm.classesNumber" placeholder="请输入班级教室"/>
      </el-form-item>
      <el-form-item label="开课时间">
        <el-date-picker
            v-model="updataForm.startTime"
            type="date"
            placeholder="请选择开课时间"
            :size="size"
        />
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker
            v-model="updataForm.finishTime"
            type="date"
            placeholder="请选择结课时间"
            :size="size"
        />
      </el-form-item>
      <el-form-item label="班主任">
        <el-select
            style="width: 200px"
            v-model="updataForm.empId"
            placeholder="请选择班主任"
            clearable
        >
          <el-option
              v-for="(item, index) in emps"
              :key="index"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormUpdata = false">取消</el-button>
        <el-button :plain="true" type="primary" @click="updataClassesOk">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>

</template>


<style scoped>

</style>